Modules

import

Let's start by using a module.

There is a module called sample_module in the same directory as this notebook. Inside it there is a function called sample_function.

Import the function and call it to see what happens. Can you do the import in two different ways?


In [5]:
import sys
sys.path.append('../exercises')
import sample_module
sample_module.sample_function()


Nobody expects the Spanish inquisition!

import as

It is possible to rename the function you are importing by using the syntax

from module import function_name as another_function_name

Go ahead and import sample_function using a more descriptive name and call it.


In [6]:
from sample_module import sample_function as samp_func
samp_func()


Nobody expects the Spanish inquisition!

Creating a module

Now create a module called mymodule (i.e. mymodule.py) using the text editor functionality of Jupyter Notebooks.

Add the following code to the module.

def add(a, b):
    return a + b

Save the file and import your newly created module in the cell below.

If you want you can also use a more inventive name than mymodule.py.


In [ ]:

Extra: reloading the module

Add a new function subtract to your above module and try to import it again. Are you able to use the subtract function?


In [ ]:

Python keeps track of modules that are imported, and performs the actual import only with the first import mymodule statement. If a module is modified during an interactive session, module needs to be explicitly reloaded in order to changes take effect. Reloading can be done with the function reload in the built-in module importlib:


In [ ]:
from importlib import reload
reload(mymodule)